package com.technology.education.ui.common.board_video

import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import com.technology.education.data.AppData
import com.technology.education.data.SpKeys
import com.technology.education.databinding.ActivityBoardVideoBinding
import com.technology.education.ext.*
import com.technology.education.ui.teacher.upload_answer.UploadAnswerActivity
import com.technology.education.utils.MediaUtils
import com.tencent.trtc.TRTCCloud
import com.tencent.trtc.TRTCCloudDef.*
import com.tencent.trtc.TRTCCloudListener
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity
import me.hgj.jetpackmvvm.util.startActivity

/**
 *@author:create by BZY
 *Date: 2022/3/24 09
 */
class BoardVideoActivity : BaseVmDbActivity<BoardVideoViewModel, ActivityBoardVideoBinding>() {
    private var mTRTCCloud: TRTCCloud? = null
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.roomId = intent.getStringExtra("roomId") ?: ""
        mViewModel.orderId = intent.getStringExtra("orderId") ?: ""
        mDatabind.vm = mViewModel
        mDatabind.click = BoardClick()
        mViewModel.showWait.set(intent.getBooleanExtra("wait", false))
        if (intent.getBooleanExtra("wait", false)) {
            //如果需要等待,则展示待接听页面,同时播放音乐
            MediaUtils.playSound(this)
        } else {
            initData()
        }

    }

    private fun initData() {
        enterRoom()
    }

    private fun enterRoom() {
        mTRTCCloud = TRTCCloud.sharedInstance(applicationContext)
        mTRTCCloud?.setListener(object : TRTCCloudListener() {
            override fun onRemoteUserEnterRoom(userId: String?) {
                super.onRemoteUserEnterRoom(userId)
                showLog("onRemoteUserEnterRoom---$userId")
            }

            override fun onRemoteUserLeaveRoom(userId: String?, reason: Int) {
                super.onRemoteUserLeaveRoom(userId, reason)
                notifyDialog("对方已离开房间,是否结束辅导?") {
                    finishVideo()
                }
            }

            override fun onUserVideoAvailable(userId: String?, available: Boolean) {
                super.onUserVideoAvailable(userId, available)
                if (available) {
                    mDatabind.videoOther.visibility = View.VISIBLE
                    mTRTCCloud?.setRemoteRenderParams(userId?:"",TRTC_VIDEO_STREAM_TYPE_BIG,TRTCRenderParams().apply {
                        fillMode= TRTC_VIDEO_RENDER_MODE_FIT
                    })
                    mTRTCCloud?.startRemoteView(
                        userId ?: "",
                        TRTC_VIDEO_STREAM_TYPE_BIG,
                        mDatabind.videoOther
                    )
                } else {
                    mDatabind.videoOther.visibility = View.GONE
                    mTRTCCloud?.stopRemoteView(userId ?: "", TRTC_VIDEO_STREAM_TYPE_BIG)
                }
            }
        })
        val trtcParams = TRTCParams()
        trtcParams.sdkAppId = AppData.SDK_ID
        trtcParams.userId = AppData.USER_ID
        trtcParams.roomId = mViewModel.roomId.toInt()
        trtcParams.userSig = AppData.IM_SIGN
        mTRTCCloud?.setNetworkQosParam(TRTCNetworkQosParam().apply {
            preference = TRTC_VIDEO_QOS_PREFERENCE_SMOOTH
        })
        mTRTCCloud?.setVideoEncoderParam(TRTCVideoEncParam().apply {
            videoResolution = TRTC_VIDEO_RESOLUTION_480_360
        })

        mTRTCCloud?.enterRoom(trtcParams, TRTC_APP_SCENE_VIDEOCALL)
        requestPermissions(
            arrayOf(
                android.Manifest.permission.CAMERA,
                android.Manifest.permission.RECORD_AUDIO
            ), 1122
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mTRTCCloud?.startLocalPreview(mViewModel.fontCamera, mDatabind.videoMain)
            mTRTCCloud?.startLocalAudio(TRTC_AUDIO_QUALITY_SPEECH)
        }
    }

    private fun exitRoom() {
        mTRTCCloud?.apply {
            stopLocalAudio()
            stopLocalPreview()
            exitRoom()
            setListener(null)
        }
        mTRTCCloud = null
        TRTCCloud.destroySharedInstance()
    }


    inner class BoardClick {

        fun addNote() {
            startActivity(UploadAnswerActivity::class, Pair("id", mViewModel.orderId))
        }

        fun reject() {
            toast("您已拒绝视频辅导")
            MediaUtils.stop()
            rejectVideo()
            finish()
        }

        fun accept() {
            MediaUtils.stop()
            acceptVideo()
            initData()
            mViewModel.showWait.set(false)
        }


        /**
         * 结束辅导,弹出进行提醒
         */
        fun finish() {
            notifyDialog("是否要结束当前辅导?") {
                finishVideo()
            }
        }

        /**
         * 切换前后摄像头
         */
        fun switchCamera() {
            if (mViewModel.cameraOpen.get()) {
                mViewModel.fontCamera = !mViewModel.fontCamera
                mTRTCCloud?.deviceManager?.switchCamera(mViewModel.fontCamera)
            }
        }

        /**
         * 开启或关闭摄像头
         */
        fun cameraStatus() {
            mViewModel.cameraOpen.set(!mViewModel.cameraOpen.get())
            if (mViewModel.cameraOpen.get()) {
                mTRTCCloud?.startLocalPreview(true, mDatabind.videoMain)
                mDatabind.videoMain.visibility = View.VISIBLE
            } else {
                mDatabind.videoMain.visibility = View.GONE
                mTRTCCloud?.stopLocalPreview()
            }
        }
    }

    /**
     * 结束辅导,如果是学生则直接退出房间,
     * 如果是教师,则调用接口后退出房间,同时解散群组
     *
     */
    private fun finishVideo() {
        if (AppData.MEMBER_TYPE == "0") {
            finish()
        } else {
            finish()
            return
            mViewModel.finish()
        }

    }


    override fun onDestroy() {
        exitRoom()
        MediaUtils.release()
        super.onDestroy()
    }

    override fun showLoading(message: String) {
        showLoadingExt()
    }

    override fun dismissLoading() {
        dismissLoading()
    }

    override fun finish() {
        postEventBus(SpKeys.REFRESH_ORDER_DETAIL, mViewModel.orderId)
        super.finish()
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            if (it) {
                finish()
            }
        }
    }

    override fun onBackPressed() {
        return
    }
}